package com.eep.common;

import java.io.FileInputStream;
import java.util.Properties;

/**
 * Reads properties (key/value pairs) from file.
 */
public class PropertyReader {

    private static final String DEFAULT_PROPERTY_FILE_LOCATION = "/com/eep/resources/config.properties";
    private static final String OVERLOADED_PROPERTY_FILE_KEY = "overloaded.properties";
    private static PropertyReader instance;
    private Properties properties;

    /**
     * This class is a singleton.  Use getInstance() to access the properties
     * from within your code.
     * @return
     */
    public static final PropertyReader getInstance() {
        if (instance == null) {
            instance = new PropertyReader();
        }
        return instance;
    }

    /**
     * Private constructor forces this class to be used as a singleton pattern.
     * Use PropertyReader.getInstance() to use this class in your code.
     */
    private PropertyReader() {
        properties = new Properties();
        // Search the system properties to check to see if an overwritten
        // property file has been set as a java command at runtime from the
        // command line.
        // E.g., java -jar app.jar -Doverloaded.properties=C:\myProps.properties
        // If non is found, use the default property file, saved as a resource
        // in the jar file.
        String propertyFile = System.getProperty(OVERLOADED_PROPERTY_FILE_KEY);
        try {
            if (propertyFile == null) {
                properties.load(this.getClass().getResourceAsStream(DEFAULT_PROPERTY_FILE_LOCATION));
            } else {
                properties.load(new FileInputStream(propertyFile));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Attempts to read a property by key name from the properties file.
     * Returns null if the property does not exist.
     * @param keyName
     * @return
     */
    public String getString(String keyName) {
        String value = properties.getProperty(keyName);
        return value;
    }

    public Boolean getBoolean(String keyName) {
        String valueStr = properties.getProperty(keyName);
        Boolean value = null;
        if (valueStr != null) {
            value = Boolean.parseBoolean(valueStr);
        }
        return value;
    }
}
